package pl.mchaniewski.ryneczek.web;

import javax.faces.application.FacesMessage;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.DateUtil;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;

@Component
@Scope("request")
public class LoginBean extends FormButton {
    private UserService userService;
    private AuthenticationManager authenticationManager;
    @NotNull(message = "{loginbean.loginNotNull}")
    private String login;
    @NotNull(message = "{loginbean.passNotNull}")
    private String pass;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setAuthenticationManager(
            AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    @PreAuthorize("isAnonymous()")
    public String validate() {
        User user = userService.findByLogin(getLogin().toLowerCase());
        if (user == null || !user.getPass().equals(getPass())) {
            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("loginbean.wronLoginOrPass"),
                    FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.SAME_PAGE;
        } else {
            user.setLastLogin(DateUtil.getNow());
            userService.save(user);

            try {
                Authentication request = new UsernamePasswordAuthenticationToken(
                        user.getLogin(), user.getPass());
                Authentication result = authenticationManager
                        .authenticate(request);
                SecurityContextHolder.getContext().setAuthentication(result);
            } catch (AuthenticationException ex) {
                FacesMessageUtil.addMessage(getButton(),
                        I18nUtil.getLocalizedMessage("loginbean.blocked"),
                        FacesMessage.SEVERITY_ERROR);

                return NavigationUtil.SAME_PAGE;
            }
        }

        return NavigationUtil.facesRedirectTo(NavigationUtil.INDEX);
    }

}
